<?php
declare (strict_types=1);

namespace app\service;

use League\OAuth2\Client\Provider\GenericProvider;
use League\OAuth2\Client\Token\AccessToken;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class PyService{

    // 配置提供商
    private $url = '8.155.165.248:5000';
    private $clientId;//从配置读取APP ID
    private $clientSecret;// APP Key
    private $redirectUri;//与QQ互联一致

    public function __construct()
    {
//        $this->apikey = env('AI.ALIAPIKey');
//        if(empty($this->apikey)){
//            throw new \Exception("密钥不存在");
//        }
        $this->clientId = env('QQ_APPID');
        $this->clientSecret = env('QQ_APPKEY');
        $this->redirectUri = 'http://www.okshiwen.cn/';
        $this->provider = new GenericProvider([
            'clientId'     => $this->clientId,     // 从配置读取APP ID
            'clientSecret' => $this->clientSecret,    // APP Key
            'redirectUri'  => $this->redirectUri, // 与QQ互联一致
            'urlAuthorize' => 'https://graph.qq.com/oauth2.0/authorize',
            'urlAccessToken' => 'https://graph.qq.com/oauth2.0/token',
            'urlResourceOwnerDetails' => 'https://graph.qq.com/oauth2.0/me'
        ]);
    }

    public function douyin($str){
        if (strpos($str, '抖音') !== false) {
            // 使用正则表达式匹配抖音链接
            preg_match('/https:\/\/v\.douyin\.com\/[a-zA-Z0-9_\/\-]+/', $str, $matches);

            if (!empty($matches)) {
                $douyinUrl = $matches[0];
                // 去除链接末尾可能存在的斜杠
                $douyinUrl = rtrim($douyinUrl, '/');
                return $douyinUrl;
            }
        }
        if(strpos($str, '小红书') !== false){
            $pattern = '/https?:\/\/(?:xhslink\.com|www\.xiaohongshu\.com)[^\s]+/';
            preg_match($pattern, $str, $matches);
            return $matches[0];
        }
        return $str;
    }

    /**
     * @return GenericProvider
     */
    public function getVideo($url)
    {
//        $fileType = 'image'; // 或 'video'
//        $subDir = 'wxmini';  // 指定上传到 wxmini 目录
//        $index = 0;          // 文件索引，用于生成唯一文件名
        //$url = 'https://www.douyin.com/note/7381393282754006284';图文
        //$url = 'https://v.douyin.com/EgEUx5scwIs';视频
        //$url = 'https://www.xiaohongshu.com/explore/6460df11000000001300ed1f?xsec_token=ABxb-DbURbqh4t2lXNywLSOwfQVMszrn4lRahjwTN3yxk=&xsec_source=pc_cfeed';视频
        //$url = 'https://www.xiaohongshu.com/explore/645b62a90000000027011861?xsec_token=ABcj3DaCs_8WlMQvWO3OLIGHGrA5AyFtOoz4Mscx-Hpyo=&xsec_source=pc_cfeed';图文

        $url = $this->douyin($url);
        $parm = [
            'url' =>$url,
        ];
        $res = curlPost($this->url.'/api/parse',json_encode($parm));
        $response = $res['response'];
        $data = json_decode($response, true); // true 表示返回数组
        Log::channel('wx')->info($data);
        $image_urls = isset($data['url']) ? $data['url'] : [];
        $media_type = isset($data['media_type']) ? $data['media_type'] : 'video';
        $video_url = isset($data['url']) ? $data['url'] : '';
        $platform = isset($data['platform']) ? $data['platform'] : 'douyin';

        $list = [
            'image_urls' => $image_urls,
            'media_type' => $media_type,
            'title' => isset($data['title']) ? $data['title'] : '-',
            'video_url' => $video_url,
            'platform' => $platform,
        ];
        return $list;
    }

    public function downloadVideo($key){
        $info = DB::table('box_video')->where(['key'=>$key])->find();
        if(!empty($info)){
            if($info['media_type'] == 1){
                $info['url_data'] = json_decode($info['url_data'],true);
            }
        }
        return $info;
    }

    //上传文件
    public function uploadOss($url,$media_type,$key){
        if($media_type == 'image'){
            $res = (new OssService())->batchUploadFromUrls($url,'image','wxmini');
            $url_data = [];
            if(!empty($res['success'])){
                foreach ($res['success'] as $v){
                    $url_data[] = $v['oss_url'];
                }
            }
            $media_type = 1;
            $url_data = json_encode($url_data);
        }else{
            $res = (new OssService())->uploadSingleFile($url,'video','wxmini',0);
            $url_data = $res['oss_url'];
            $media_type = 2;
        }
        if(empty($url_data)){
            return 'failure';
        }
        $info = [
            'key' =>$key,
            'media_type' =>$media_type,
            'url_data' =>$url_data,
            'addtime' =>date('Y-m-d H:i:s'),
        ];
        DB::table('box_video')->insertGetId($info);
        return 'success';
    }

    //翻译
    public function translate(){
//        $parm = [
//            'from' =>'zh',
//            'query' =>'你好',
//            'source' =>'txt',
//            'to' =>'jp',
//        ];
        $parm = [
            'kw' =>'你在做什么？',
        ];
        $url = 'https://fanyi.baidu.com/sug';
        $headers =  [
            'User-Agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
        ];
        $res = curlPost($url,json_encode($parm),$headers);
        print_r($res);die;
        $response = $res['response'];
        $data = json_decode($response, true); // true 表示返回数组
        return $data;
    }


}